package com.bj58.data.emailreports.dao;


import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

import javax.sql.DataSource;
import java.sql.DriverManager;

import org.apache.commons.dbcp.BasicDataSourceFactory;
//import org.apache.log4j.Logger;

import com.bj58.wf.log.Log;
import com.bj58.wf.log.LogFactory;
import com.bj58.groupbuy.util.PathUtil;

/**
 * dbcp数据库连接池的实现类(获取源数据库连接池)
 * 
 * @author HL
 */
public class SrcDbPool
{
	
	static AtomicInteger testCount = new AtomicInteger();
	
	static DataSource dataSource_db_94_data_app = null;  //26 101
	static DataSource dataSource_db_131_data_bi = null;  //104
	static DataSource dataSource_hive_data_dw = null;    //hive 
	static DataSource dataSource_db_68_bi_sys = null;  //16
	static DataSource dataSource_db_131_ors = null;  //16  dbwww58com_online_revenue_stats
	static DataSource dataSource_db_94_data_tmp = null;  
	static DataSource dataSource_db_133_dm_sales = null; 
	
	private static SrcDbPool m_db = null;
	//private static Logger log = Logger.getLogger(SrcDbPool.class);
	private static Log log = LogFactory.getLog(SrcDbPool.class);

    public enum DBType {
    		
    	db_94_data_app("srcconnpool_db_94_data_app.properties",1),
    	db_131_data_bi("srcconnpool_db_131_data_bi.properties",2),
    	hive_data_dw("srcconnpool_hive_data_dw.properties",3),
    	db_68_bi_sys("srcconnpool_db_68_bi_sys.properties",4),
    	db_131_ors("srcconnpool_db_131_ors.properties",5), 	
    	db_94_data_tmp("srcconnpool_db_94_data_tmp.properties",6),
    	db_133_dm_sales("srcconnpool_db_133_dm_sales.properties",7);
	
        private final int value;
        private final String configPath;

        DBType(String configPath,int value){
    		this.configPath =  PathUtil.getWFNamespaceFolder()+"/"+configPath;
    		this.value = value;
    	}
        public int getValue() {
            return value;
        }
    	public String getConfigPath() {
    		return configPath;
    	}
    }
	
	public synchronized static SrcDbPool getInstance()
	{
		if(m_db== null){
			m_db = new SrcDbPool();
		}
		return m_db;
	}	
		
	public Connection getConnection(int type) 
	{
		Connection conn = null;
		DataSource dataSource = null;
		try
		{
			if(type == 1){
				if(null == dataSource_db_94_data_app){
					dataSource_db_94_data_app = createDataSource(type);
				}
				dataSource = dataSource_db_94_data_app;
			}
			else if(type == 2){
				if(null == dataSource_db_131_data_bi){
					dataSource_db_131_data_bi = createDataSource(type);
				}
				dataSource = dataSource_db_131_data_bi;
			}
			else if(type == 3){
				if(null == dataSource_hive_data_dw){
					dataSource_hive_data_dw = createDataSource(type);
				}
				dataSource = dataSource_hive_data_dw;
				if(DriverManager.getLoginTimeout() != 0){
					synchronized(DriverManager.class){
						DriverManager.setLoginTimeout(0);
					}			
				}
			}
			else if(type == 4){
				if(null == dataSource_db_68_bi_sys){
					dataSource_db_68_bi_sys = createDataSource(type);
				}
				dataSource = dataSource_db_68_bi_sys;
			}
			else if(type == 5){
				if(null == dataSource_db_131_ors){
					dataSource_db_131_ors = createDataSource(type);
				}
				dataSource = dataSource_db_131_ors;
			}
			else if(type == 6){
				if(null == dataSource_db_94_data_tmp){
					dataSource_db_94_data_tmp = createDataSource(type);
				}
				dataSource = dataSource_db_94_data_tmp;
			}
			else if(type == 7){
				if(null == dataSource_db_133_dm_sales){
					dataSource_db_133_dm_sales = createDataSource(type);
				}
				dataSource = dataSource_db_133_dm_sales;
			}
			
			conn = dataSource.getConnection();
		}catch (Exception e) {
			log.error("DbPool: error when got a connection from DB pool.",e);
		}		
		return conn;
	}

	private static HashMap<Integer, DBType> dbConfMap = new HashMap<Integer, DBType>();
	static{
    	for(DBType db : DBType.values()){
    		dbConfMap.put(db.getValue(), db);
    	}
    }

	/**
	 * 创建一个新的数据库连接池
	 * 
	 * @param name JNDI的搜索名
	 * @param record 数据库连接池的基本信息
	 * @param constants 系统内置的环境管理类
	 * @return 新的数据库连接池，null表示创建失败
	 */
	private static DataSource createDataSource(int type)
	{
		DataSource dataSource = null;
		try
		{
			File propfile = null;
			String path = "";
			DBType dbConfig = dbConfMap.get(type);				
			path = dbConfig.getConfigPath();

			propfile = new File(path);	
			Properties p = new Properties();
			FileInputStream fis = new FileInputStream(propfile);
			p.load(fis);
			fis.close();
					
			//DBCP连接池的自我检测
			p.setProperty("validationQuery", "select 1");
			p.setProperty("testWhileIdle", "true");
			p.setProperty("testOnBorrow", "false");
			p.setProperty("testOnReturn", "true");
			p.setProperty("timeBetweenEvictionRunsMillis", "30000");
			p.setProperty("minEvictableIdleTimeMillis", "1800000");
			p.setProperty("numTestsPerEvictionRun", "3");
			p.setProperty("removeAbandoned", "true");
			p.setProperty("removeAbandonedTimeout", "60");
			
			dataSource = BasicDataSourceFactory.createDataSource(p);			
		} 
		catch (Exception e){
			e.printStackTrace();
		}
		return dataSource;
	}
	
	/**
	 * 关闭连接
	 * 
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public static void close(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			rs = null;
			st = null;
			conn = null;
			log.debug("关闭数据库资源异常", e);
		}
	}
	
}
